package com.youlai.boot.system.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.youlai.boot.common.annotation.Log;
import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.common.exception.BusinessException;
import com.youlai.boot.common.result.ExcelResult;
import com.youlai.boot.common.util.ExcelUtils;
import com.youlai.boot.excel.Sheet1DTO;
import com.youlai.boot.excel.Sheet2DTO;
import com.youlai.boot.system.listener.UserImportListener;
import com.youlai.boot.system.model.dto.UserImportDTO;
import com.youlai.boot.system.model.vo.SysDashboardVO;
import com.youlai.boot.system.service.SysYouqitouziService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.youlai.boot.system.model.form.SysYouqitouziForm;
import com.youlai.boot.system.model.query.SysYouqitouziQuery;
import com.youlai.boot.system.model.vo.SysYouqitouziVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 油气项目前端控制层
 *
 * @author lwb
 * @since 2025-05-29 21:40
 */
@Tag(name = "油气项目接口")
@RestController
@RequestMapping("/api/v1/sysYouqitouzis")
@RequiredArgsConstructor
public class SysYouqitouziController {

    private final SysYouqitouziService sysYouqitouziService;

    @Operation(summary = "油气项目分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPerm('system:sysYouqitouzi:query')")
    public PageResult<SysYouqitouziVO> getSysYouqitouziPage(SysYouqitouziQuery queryParams) {
        IPage<SysYouqitouziVO> result = sysYouqitouziService.getSysYouqitouziPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "下载模版")
    @GetMapping("/download")
    @PreAuthorize("@ss.hasPerm('system:sysYouqitouzi:download')")
    public void download(HttpServletResponse response) throws IOException {
        String fileName = "项目数据导入模版.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        String fileClassPath = "templates" + File.separator + "excel" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }

    @Operation(summary = "导入")
    @PostMapping("/import")
    public Result<Boolean> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new BusinessException("文件为空，请上传有效的Excel文件");
        }

        List<Sheet1DTO> sheet1Data;
        List<Sheet2DTO> sheet2Data;

        byte[] fileBytes = file.getBytes();
        try (InputStream is1 = new ByteArrayInputStream(fileBytes);
             InputStream is2 = new ByteArrayInputStream(fileBytes)) {

            sheet1Data = EasyExcel.read(is1)
                    .head(Sheet1DTO.class)
                    .headRowNumber(2)  // 跳过前两行
                    .sheet(0)
                    .doReadSync();

            sheet2Data = EasyExcel.read(is2)
                    .head(Sheet2DTO.class)
                    .headRowNumber(2)
                    .sheet(1)
                    .doReadSync();
        }

        // 调用服务层处理导入的数据
        boolean result = sysYouqitouziService.importExcel(sheet1Data, sheet2Data);

        return Result.success(result);
    }

    @Operation(summary = "获取油气项目表单数据")
    @GetMapping("/{id}/form")
    @PreAuthorize("@ss.hasPerm('system:sysYouqitouzi:edit')")
    public Result<SysYouqitouziForm> getSysYouqitouziForm(
            @Parameter(description = "油气项目ID") @PathVariable Long id
    ) {
        SysYouqitouziForm formData = sysYouqitouziService.getSysYouqitouziFormData(id);
        return Result.success(formData);
    }

    @Operation(summary = "修改油气项目")
    @PutMapping(value = "/{id}")
    @PreAuthorize("@ss.hasPerm('system:sysYouqitouzi:edit')")
    public Result<Void> updateSysYouqitouzi(
            @Parameter(description = "油气项目ID") @PathVariable Long id,
            @RequestBody @Validated SysYouqitouziForm formData
    ) {
        boolean result = sysYouqitouziService.updateSysYouqitouzi(id, formData);
        return Result.judge(result);
    }

    @Operation(summary = "删除油气项目")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('system:sysYouqitouzi:delete')")
    public Result<Void> deleteSysYouqitouzis(
            @Parameter(description = "油气项目ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = sysYouqitouziService.deleteSysYouqitouzis(ids);
        return Result.judge(result);
    }

    @Operation(summary = "首页统计")
    @GetMapping("/dashboard")
    public Result<SysDashboardVO> dashboard(SysYouqitouziQuery queryParams) {
        SysDashboardVO dashboardVO = sysYouqitouziService.dashboard(queryParams);
        return Result.success(dashboardVO);
    }
}
